﻿Imports System.Collections.ObjectModel
Imports System.Windows.Threading
Imports FL_8x0.Common
Imports FL_8x0.FL_830.ViewModel
Imports FL_8x0.Model
Imports GalaSoft.MvvmLight
Imports GalaSoft.MvvmLight.Command
Imports GalaSoft.MvvmLight.Messaging

Namespace FL_8x0.Viewmodel

    Public Class MainViewModel
        Inherits ViewModelBase

        Private _menuModels As ObservableCollection(Of MenuModel)   '菜单列表
        Private _menuModel As MenuModel                             '当前菜单
        Private _preMenuModel As MenuModel                          '上一个菜单
        Private _linkStatus As String                               '检漏仪连接状态
        Private _loginUser As String                                '登录用户

        Private _lastPage As String                                 '上一个页面

        Private _mainContent As UserControl                         '当前显示页

        Private _selectedCommand As RelayCommand(Of MenuModel)      '点击菜单触发命令


        Public Sub New()
            _loginUser = "用户名：" & g_strUserName

            Dim strJsonData = My.Computer.FileSystem.ReadAllText(g_strStartupPath & "\JSON\Machine.json", Text.Encoding.UTF8)
            Dim jsonResult = Newtonsoft.Json.Linq.JObject.Parse(strJsonData)
            SystemData.Machine = jsonResult.Item("machine")
            SystemData.Version = jsonResult.Item("version")
            If Machine <> Model_830 Then
                Dim portName As String = jsonResult.Item("portName")
                Dim baudRate As String = jsonResult.Item("baudRate")
                Dim other As String = jsonResult.Item("other")
                SystemData.strLink = portName & "," & baudRate & "," & SystemData.Machine &
                    "," & SystemData.Version & "," & other

                Database.ReopenDataBase(SystemData.g_strDatabaseProvider, SystemData.g_strDatabasePath & "\" & Machine & "\",
                                        SystemData.SUPER_USER_NAME, SystemData.SUPER_PASSWORD)
            End If


            MenuModels = New ObservableCollection(Of MenuModel)
            If InStr(g_strUserLevel, "泄漏检测") > 0 Then
                MenuModels.Add(New MenuModel("泄漏检测", "../Assets/Images/1.png", "../Assets/Images/1.1.png", "FL_8x0." & SystemData.Machine.Replace("MS", "") & ".View.LeakTestWindow"))
            End If
            If InStr(g_strUserLevel, "用户管理") > 0 Then
                MenuModels.Add(New MenuModel("用户管理", "../Assets/Images/2.png", "../Assets/Images/2.2.png", "FL_8x0.View.UserWindow"))
            End If
            If InStr(g_strUserLevel, "产品") > 0 Then
                MenuModels.Add(New MenuModel("产品管理", "../Assets/Images/3.png", "../Assets/Images/3.3.png", "FL_8x0." & SystemData.Machine & ".View.ProductWindow"))
            End If
            If InStr(g_strUserLevel, "记录管理") > 0 Then
                MenuModels.Add(New MenuModel("记录管理", "../Assets/Images/4.png", "../Assets/Images/4.4.png", "FL_8x0.View.RecordWindow"))
            End If
            If InStr(g_strUserLevel, "日志管理") > 0 Then
                MenuModels.Add(New MenuModel("日志管理", "../Assets/Images/5.png", "../Assets/Images/5.5.png", "FL_8x0.View.LogWindow"))
            End If
            If InStr(g_strUserLevel, "通用设置") > 0 Then
                MenuModels.Add(New MenuModel("系统设置", "../Assets/Images/7.png", "../Assets/Images/7.7.png", "FL_8x0." & SystemData.Machine.Replace("MS", "") & ".View.SystemWindow"))
            End If
            MenuModels.Add(New MenuModel("关闭", "../Assets/Images/9.png", "../Assets/Images/9.9.png", ""))

            MenuModel = MenuModels(0)
            MenuModel.ShowIcon = MenuModel.SelectedIcon
            _preMenuModel = MenuModel

            NavPage(MenuModel.Url)

            SelectedCommand = New RelayCommand(Of MenuModel)(Sub(m) [Select](m))

            Dim timer As DispatcherTimer = New DispatcherTimer

            timer.Interval = TimeSpan.FromMilliseconds(300)
            AddHandler timer.Tick, AddressOf FlashStatus
            timer.IsEnabled = True

            Messenger.Default.Register(Of String)(Me, "Machine-Select", Sub(machine)
                                                                            If machine.Contains("MS") Then
                                                                                MenuModels(0).Url = "FL_8x0." & machine.Replace("MS", "") & ".View.LeakTestWindow"
                                                                                MenuModels(5).Url = "FL_8x0." & machine.Replace("MS", "") & ".View.SystemWindow"
                                                                            Else
                                                                                MenuModels(0).Url = "FL_8x0." & machine & ".View.LeakTestWindow"
                                                                                MenuModels(5).Url = "FL_8x0." & machine & ".View.SystemWindow"
                                                                            End If
                                                                            MenuModels(2).Url = "FL_8x0." & machine & ".View.ProductWindow"
                                                                            NavPage(MenuModels(0).Url)
                                                                        End Sub)
        End Sub

        '=====================================================================
        '函 数 名: FlashStatus
        '参    数: 
        '返 回 值:
        '功能描述: 刷新检漏仪连接状态
        '=====================================================================
        Private Sub FlashStatus(sender As Object, args As EventArgs)
            If Machine = Model_830 Then
                LinkStatus = "检漏仪：" & IIf(uLPU.IsServerRunning(), "运行" & IIf(uLPU.IsModbusOK(), "(正常)", "(异常)"), "停止")
            Else
                LinkStatus = "检漏仪：" & IIf(g_udtFL800Sync.IsRunning(), "运行", "停止")
            End If
        End Sub

        '=====================================================================
        '函 数 名: [Select]
        '参    数:  model 菜单
        '返 回 值:
        '功能描述: 切换菜单
        '=====================================================================
        Private Sub [Select](model As MenuModel)
            If _lastPage = "FL_8x0.FL_830.View.LeakTestWindow" Then
                If CBool(User_ReadPublicValue("退出泄漏检测提示", "False")) Then
                    If SystemData.g_strUserName <> "" Then
                        If MsgBox("确定要关闭[泄漏检测]吗？", vbYesNo, "退出") = vbNo Then
                            Exit Sub
                        End If
                    End If
                End If

                If InStr(SystemData.g_strUserLevel, "报表打印导出权限") > 0 Then '报表打印导出权限
                    If CBool(User_ReadPublicValue("导出报告提示", "False")) Then
                        Dim leakTestViewModel = TryCast(MainContent.DataContext, FL_830.ViewModel.LeakTestViewModel)

                        If leakTestViewModel.RecordList.Count > 0 Then
                            If MsgBox("有未导出报告的数据记录，是否[导出记录]？", vbYesNo, "保存") = vbYes Then
                                leakTestViewModel.SaveResult() '保存记录
                            End If
                        End If
                    End If
                End If
            End If
            _preMenuModel.ShowIcon = _preMenuModel.UnSelectedIcon
            MenuModel = model
            MenuModel.ShowIcon = model.SelectedIcon

            If model.Url <> "" Then
                NavPage(model.Url)
            End If
            If model.Title = "关闭" Then
                log.WriteLogInfo("关闭", "用户名:" & SystemData.g_strUserName) 'log痕迹记录
                If CBool(User_ReadPublicValue("程序退出提示", "False")) Then
                    If MsgBox("确定要关闭系统吗？", vbYesNo, "退出") = vbNo Then
                        model.ShowIcon = model.UnSelectedIcon
                        MenuModel = _preMenuModel
                        MenuModel.ShowIcon = _preMenuModel.SelectedIcon
                        Exit Sub
                    End If
                End If
                Application.Current.Shutdown()
            End If
            _preMenuModel = model
        End Sub

        '=====================================================================
        '函 数 名: NavPage
        '参    数: name url
        '返 回 值:
        '功能描述: 反射显示UserControl
        '=====================================================================
        Private Sub NavPage(ByVal name As String)

            If String.IsNullOrEmpty(name) Then
                Return
            End If
            _lastPage = name
            Dim type As Type = Type.[GetType](name)
            MainContent = CType(Activator.CreateInstance(type), UIElement)
        End Sub


        Public Property MenuModel As MenuModel
            Get
                Return _menuModel
            End Get
            Set
                _menuModel = Value
            End Set
        End Property

        Public Property MenuModels As ObservableCollection(Of MenuModel)
            Get
                Return _menuModels
            End Get
            Set
                _menuModels = Value
            End Set
        End Property

        Public Property SelectedCommand As RelayCommand(Of MenuModel)
            Get
                Return _selectedCommand
            End Get
            Set
                _selectedCommand = Value
            End Set
        End Property

        Public Property MainContent As UserControl
            Get
                Return _mainContent
            End Get
            Set
                _mainContent = Value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property LinkStatus As String
            Get
                Return _linkStatus
            End Get
            Set(value As String)
                _linkStatus = value
                RaisePropertyChanged()
            End Set
        End Property

        Public Property LoginUser As String
            Get
                Return _loginUser
            End Get
            Set
                _loginUser = Value
            End Set
        End Property
    End Class
End Namespace